import EventEmitter from 'events';

export type SelectionType = {
  anchor: number,
  focus: number
}

export class SelectionModel extends EventEmitter {
  private _selection : SelectionType | null = null;

  constructor () {
    super();
    this._selection = { anchor: 0, focus: 0 };
  }

  _emitSelectionChangeEvent () : void {
    this.emit('selection_change');
  }

  getSelection () : SelectionType | null {
    return this._selection == null ? this._selection : { ...this._selection };
  }

  setSelection (selection : SelectionType | null) : void {
    if (selection && this._selection && 
      this._selection.anchor === selection.anchor && 
      this._selection.focus === selection.focus) {
      return;
    }
    this._selection = selection ? { ...selection } : null;
    this._emitSelectionChangeEvent();
  }

  // 光标是否重叠
  isCollapse () : boolean {
    return this._selection && this._selection.anchor === this._selection.focus || false;
  }

  // 光标是否为反向选择
  isBackward () : boolean {
    return this._selection && this._selection.anchor > this._selection.focus || false;
  }
}

export default SelectionModel;